package org.example.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 转发服务端
 */
public class Demo2Server {
    /**
     * 选择器
     */
    private final Selector selector;
    /**
     * 服务Socket
     */
    private final ServerSocketChannel serverSocketChannel;

    /**
     * 初始化构造函数
     */
    Demo2Server() {
        try {
            //开启选择器
            selector = Selector.open();
            //开启服务Socket,设置端口,设置非阻塞
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(10040));
            serverSocketChannel.configureBlocking(false);
            //服务Socket注册至选择器
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * main
     *
     * @param args args
     */
    public static void main(String[] args) {
        //创建服务端
        Demo2Server demo2Server = new Demo2Server();
        //监听
        demo2Server.listen();
    }

    /**
     * 监听
     */
    public void listen() {
        try {
            //服务Socket未关闭,则轮询选择器
            while (!serverSocketChannel.socket().isClosed()) {
                //开启选择器
                int count = selector.select();
                if (count > 0) {
                    //遍历选择器时间
                    for (SelectionKey key : selector.selectedKeys()) {
                        //连接事件
                        if (key.isAcceptable()) {
                            //获取socket通道,并设置非阻塞
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            //注册读取事件至选择器
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + "上线");
                        }
                        //读取事件
                        if (key.isReadable()) {
                            read(key);
                        }
                        selector.selectedKeys().remove(key);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读
     *
     * @param key 选择器key
     */
    public void read(SelectionKey key) {
        try {
            //获取socket通道
            SocketChannel socketChannel = (SocketChannel) key.channel();
            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //读取数据至缓冲区
            int read = socketChannel.read(byteBuffer);
            if (read > -1) {
                //获取消息并转发
                String msg = new String(byteBuffer.array());
                System.out.println("读取数据" + msg);
                transmit(msg, socketChannel);
            } else {
                System.out.println(socketChannel.getRemoteAddress() + "离线");
                key.cancel();
                socketChannel.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 转发
     *
     * @param msg           信息
     * @param socketChannel socket通道
     * @throws IOException io异常
     */
    public void transmit(String msg, SocketChannel socketChannel) throws IOException {
        System.out.println("开始转发消息");
        //遍历选择器key
        for (SelectionKey key : selector.keys()) {
            //获取通道
            Channel channel = key.channel();
            //如为socket通道并且非发送方,则转发
            if (channel instanceof SocketChannel && !channel.equals(socketChannel)) {
                //创建缓冲区
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                //写入通道
                ((SocketChannel) channel).write(byteBuffer);
                System.out.println("转发消息" + ((SocketChannel) channel).getRemoteAddress() + ":" + msg);
            }

        }
    }
}
